package com.powernobug.util;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.converters.DateConverter;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.Date;
import java.util.Map;

/**
 * @Author: 肖云戈
 * @CreateTime: 2024-08-21
 * @Description:
 */
public class QueryParamPackageUtil {
    private QueryParamPackageUtil() {}

    // 对BeanUtils 设置 Date 类型的映射格式，否则不识别
    static {
        DateConverter dateConverter = new DateConverter(null);
        dateConverter.setPatterns(new String[] {"yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss"});
        ConvertUtils.register(dateConverter, Date.class);
    }

    public static <T> T packParams(Class<T> clazz, HttpServletRequest request) {
        // 获取参数Map
        Map<String, String[]> parameterMap = request.getParameterMap();
        try {
            // 获取无参构造器
            Constructor<T> constructor = clazz.getDeclaredConstructor();
            // 使用无参构造器实例化创建实例(对象)
            T instance = constructor.newInstance();

            // 调用BeanUtils来讲Map中的值封装给instance
            BeanUtils.copyProperties(instance, parameterMap);
            return instance;
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        } catch (InstantiationException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }
}
